//
//  SURateAlertVC.m
//  GC_OC
//
//  Created by Kris on 2023/4/28.
//

#import "SURateAlertVC.h"
#import "SURateCell.h"
#import "SULogCell.h"
#import "SUClockCell.h"
#import "SUAffixCell.h"

#import "SURateModel.h"
#import "SUPlayerManager.h"


@interface SURateAlertVC () <UITableViewDelegate, UITableViewDataSource>
@property (weak, nonatomic) IBOutlet UILabel *titleLabel;
@property (weak, nonatomic) IBOutlet UILabel *subTitleLabel;
@property (weak, nonatomic) IBOutlet UIView *bgView;

@property (nonatomic, strong) UITableView *tableView;

@property (nonatomic, strong) NSMutableArray<SURateModel *> *dataArr;
@property (nonatomic, strong) NSMutableArray<NSDictionary *> *songArr;
@property (nonatomic, strong) NSMutableArray<SURateModel *> *clockArr;

@property (weak, nonatomic) IBOutlet UIButton *resetBtn;
@property (nonatomic, strong) UILabel *timeLabel;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *bgHeight;

@property (nonatomic, strong) NSIndexPath *indexPath;
@end

@implementation SURateAlertVC
{
    NSTimer *_timer;
}

- (IBAction)didClickBtn:(UIButton *)sender
{
    [self.view removeFromSuperview];
    [self removeFromParentViewController];
}

- (IBAction)didClickReset:(UIButton *)sender
{
    [self.tableView scrollToRowAtIndexPath:self.indexPath atScrollPosition:UITableViewScrollPositionMiddle animated:YES];
}


- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    
    [_timer setFireDate:[NSDate distantFuture]];
}

- (void)viewDidLayoutSubviews
{
    if (self.tagInt == 2) {
        NSArray *arr = [self.tableView indexPathsForVisibleRows];
        self.resetBtn.hidden = [arr containsObject:self.indexPath];
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    self.bgHeight.constant = 400;
    
    if (self.tagInt == 1) {
        self.dataArr = [NSMutableArray array];
        
        NSArray *arr = @[@"0.75", @"1.0", @"1.25", @"1.5", @"2.0", @"2.5", @"3.0"];
        NSArray *arr1 = @[@"微慢", @"正常", @"微快", @"偏快", @"很快", @"超快", @"最快"];
        for (int i = 0 ; i < arr.count; i++) {
            SURateModel *model = [SURateModel new];
            model.title = arr[i];
            model.des = arr1[i];
            if ([SUPlayerManager manager].saveRate == [arr[i] floatValue]) {
                model.isSelect = YES;
            } else {
                model.isSelect = NO;
            }
            [self.dataArr addObject:model];
        }
        
        self.titleLabel.text = @"倍数设定";
        self.subTitleLabel.text = @"（根据听觉，调整速度）";
    } else if (self.tagInt == 2) {
        self.songArr = [NSMutableArray array];
        self.songArr = [SUPlayerManager manager].songList;
        if (self.songArr.count > 18) {
            self.bgHeight.constant = SCREEN_HEIGHT * 0.7;
        }
        
        self.titleLabel.text = @"当前播放";
        self.subTitleLabel.text = [NSString stringWithFormat:@"（%ld）", self.songArr.count];
        
        self.indexPath = [NSIndexPath indexPathForRow:[SUPlayerManager manager].currentSongIndex inSection:0];
        self.resetBtn.hidden = YES;
    } else if (self.tagInt == 3) {
        self.clockArr = [NSMutableArray array];
        NSArray *arr = @[@"不开启", @"10分钟后", @"20分钟后", @"30分钟后", @"60分钟后", @"90分钟后", @"播完当前媒体再关闭"];
        for (int i = 0 ; i < arr.count; i++) {
            SURateModel *model = [SURateModel new];
            model.title = arr[i];
            if ([[SUPlayerManager manager].saveClock isEqualToString: arr[i]]) {
                model.isSelect = YES;
            } else {
                model.isSelect = NO;
            }
            [self.clockArr addObject:model];
        }
        
        self.titleLabel.text = @"定时关闭";
        self.subTitleLabel.text = @"（计时结束后，将暂停播放歌曲）";
        
        _timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(countDownSet) userInfo:nil repeats:YES];
    } else if (self.tagInt == 4) {
        self.titleLabel.text = self.affixTitle;
        self.subTitleLabel.text = @"";
    }

    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.equalTo(self.bgView);
        make.top.equalTo(self.titleLabel.mas_bottom).offset(5);
    }];
    
    UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:CGRectMake(0, 0, SCREEN_WIDTH, 1000) byRoundingCorners:UIRectCornerTopLeft | UIRectCornerTopRight cornerRadii:CGSizeMake(15, 15)];
    CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
    maskLayer.frame = self.bgView.bounds;
    maskLayer.path = maskPath.CGPath;
    self.bgView.layer.mask = maskLayer;
}


- (void)countDownSet
{
    self.timeLabel.text = [NSString convertStringWithTime:[SUPlayerManager manager].clockLeft];
}



#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (self.tagInt == 1) {
        return self.dataArr.count;
    } else if (self.tagInt == 2) {
        return self.songArr.count;
    } else if (self.tagInt == 3) {
        return self.clockArr.count;
    } else if (self.tagInt == 4) {
        return 1;
    } else {
        return 0;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (self.tagInt == 1) {
        SURateCell *cell = [tableView dequeueReusableCellWithIdentifier:@"rateCell" forIndexPath:indexPath];
        cell.nameLabel.text = self.dataArr[indexPath.row].title;
        cell.detailLabel.text = self.dataArr[indexPath.row].des;
        cell.backgroundColor = self.dataArr[indexPath.row].isSelect?ColorFromHexAndAlpa(0x32C5FF, 0.11):ColorFromHex(0xFFFFFF);
        cell.detailLabel.textColor = self.dataArr[indexPath.row].isSelect?ColorFromHex(0x0091FF):ColorFromHexAndAlpa(0x000000, 0.25);
        cell.nameLabel.textColor = self.dataArr[indexPath.row].isSelect?ColorFromHex(0x0091FF):ColorFromHexAndAlpa(0x000000, 0.25);

        cell.selectionStyle = 0;
        return cell;
    } else if (self.tagInt == 2) {
        SULogCell *cell = [tableView dequeueReusableCellWithIdentifier:@"logCell" forIndexPath:indexPath];
        cell.nameLabel.text = self.songArr[indexPath.row][@"name"];
        cell.detailLabel.text = [NSString convertStringWithTime:[self.songArr[indexPath.row][@"audio_num"] floatValue]];
        if (indexPath.row == [SUPlayerManager manager].currentSongIndex) {
            cell.nameLabel.textColor = ColorFromHex(0x0091FF);
            cell.nameLabel.font = [UIFont systemFontOfSize:16.f weight:UIFontWeightMedium];
            cell.detailLabel.textColor = ColorFromHex(0x0091FF);
            cell.detailLabel.font = [UIFont systemFontOfSize:14.f weight:UIFontWeightRegular];
            cell.img.hidden = NO;
            cell.backgroundColor = ColorFromHexAndAlpa(0x32C5FF, 0.11);
        } else {
            cell.nameLabel.textColor = ColorFromHex(0x000000);
            cell.nameLabel.font = [UIFont systemFontOfSize:16.f weight:UIFontWeightRegular];
            cell.detailLabel.textColor = ColorFromHexAndAlpa(0x000000, 0.25);
            cell.detailLabel.font = [UIFont systemFontOfSize:10.f weight:UIFontWeightRegular];
            cell.img.hidden = YES;
            cell.backgroundColor = [UIColor whiteColor];
        }
        cell.selectionStyle = 0;
        return cell;
    } else if (self.tagInt == 3) {
        SUClockCell *cell = [tableView dequeueReusableCellWithIdentifier:@"clockCell" forIndexPath:indexPath];
        NSString *clockStr = self.clockArr[indexPath.row].title;
        cell.nameLabel.text = clockStr;
        if ([clockStr isEqualToString:@"播完当前媒体再关闭"]) {
            cell.desLabel.hidden = NO;
        } else {
            cell.desLabel.hidden = YES;
        }
    
        if ([[SUPlayerManager manager].saveClock isEqualToString:clockStr]) {
            cell.nameLabel.textColor = ColorFromHex(0x0091FF);
            cell.desLabel.textColor = ColorFromHex(0x0091FF);
            if ([clockStr isEqualToString:@"播完当前媒体再关闭"] || [clockStr isEqualToString:@"不开启"]) {
                cell.timeLabel.hidden = YES;
            } else {
                self.timeLabel = cell.timeLabel;
                self.timeLabel.text = [NSString convertStringWithTime:[SUPlayerManager manager].clockLeft];
                cell.timeLabel.hidden = NO;
            }
        } else {
            cell.nameLabel.textColor = ColorFromHex(0x000000);
            cell.desLabel.textColor = ColorFromHex(0x000000);
            cell.timeLabel.hidden = YES;
        }
                
        cell.selectionStyle = 0;
        return cell;
    } else if (self.tagInt == 4) {
        SUAffixCell *cell = [tableView dequeueReusableCellWithIdentifier:@"affixCell" forIndexPath:indexPath];
        cell.titleLabel.text = self.affixContent;
        cell.selectionStyle = 0;
        return cell;
    } else {
        return nil;
    }
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (self.tagInt == 4)
    {
        return tableView.estimatedRowHeight;
    }
    return 40;
}

#pragma mark - UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    if (self.tagInt == 1) {
        for (SURateModel *model in self.dataArr) {
            model.isSelect = NO;
        }
        
        self.dataArr[indexPath.row].isSelect = YES;
        [tableView reloadData];
        
        [SUPlayerManager manager].player.rate = self.dataArr[indexPath.row].title.floatValue;
        [SUPlayerManager manager].saveRate = self.dataArr[indexPath.row].title.floatValue;
        
        if (self.changeBlock) {
            self.changeBlock(self.dataArr[indexPath.row].title);
        }
    } else if (self.tagInt == 2) {
        
        if ([SUPlayerManager manager].currentSongIndex == indexPath.row) return;
        [SUPlayerManager manager].currentSongIndex = indexPath.row;
        
        self.indexPath = indexPath;
        [self.tableView reloadData];
        
        NSArray *arr = [self.tableView indexPathsForVisibleRows];
        self.resetBtn.hidden = [arr containsObject:self.indexPath];
        
        if (self.choseBlock) {
            self.choseBlock(0);
        }
    } else if (self.tagInt == 3) {
        if ([[SUPlayerManager manager].saveClock isEqualToString:self.clockArr[indexPath.row].title]) {
            return;
        }
        for (SURateModel *model in self.clockArr) {
            model.isSelect = NO;
        }
        self.clockArr[indexPath.row].isSelect = YES;
        [tableView reloadData];
        
        [SUPlayerManager manager].saveClock = self.clockArr[indexPath.row].title;
        
        if (self.clockBlock) {
            self.clockBlock(self.clockArr[indexPath.row].title);
        }
        
        [self.view removeFromSuperview];
        [self removeFromParentViewController];
        
    }
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    if (self.tagInt == 2) {
        NSArray *arr = [self.tableView indexPathsForVisibleRows];
        self.resetBtn.hidden = [arr containsObject:self.indexPath];
    }
}


- (UITableView *)tableView
{
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
        _tableView.backgroundColor = [UIColor clearColor];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        [self.bgView addSubview:_tableView];
        _tableView.separatorStyle = 0;
//        _tableView.scrollEnabled = NO;
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.showsHorizontalScrollIndicator = NO;
        [_tableView registerNib:[UINib nibWithNibName:@"SURateCell" bundle:nil] forCellReuseIdentifier:@"rateCell"];
        [_tableView registerNib:[UINib nibWithNibName:@"SULogCell" bundle:nil] forCellReuseIdentifier:@"logCell"];
        [_tableView registerNib:[UINib nibWithNibName:@"SUClockCell" bundle:nil] forCellReuseIdentifier:@"clockCell"];
        [_tableView registerNib:[UINib nibWithNibName:@"SUAffixCell" bundle:nil] forCellReuseIdentifier:@"affixCell"];
        [self.bgView bringSubviewToFront:self.resetBtn];
    }
    return _tableView;
}



@end
